package edu.mis.modules.cart;

import com.jfinal.core.Controller;


import java.util.*;

import edu.mis.model.*;

import edu.mis.modules.customer.CustomerController;
import edu.mis.modules.orderDetail.OrderDetailController;
import edu.mis.modules.orderDetailCustomer.OrderDetailCustomerController;
import edu.mis.modules.orderDetailRoom.OrderDetailRoomController;
import edu.mis.modules.orderList.OrderListController;
import edu.mis.modules.orderStatus.OrderStatusController;
import edu.mis.modules.room.RoomController;
import edu.mis.modules.roomStatus.RoomStatusController;
import edu.mis.modules.roomType.RoomTypeController;
import edu.mis.modules.user.UserController;
import edu.mis.util.DateUtil;


public class CartController extends Controller {




    public void index() {
        render("cart.html");
    }

    public void list(){
        User user = UserController.service.findUserByName((String)getSessionAttr("loginUserName"));
        Cart cart = getSessionAttr("cart");
        Date[] checkDate = (Date[]) ((getSessionAttr("checkDate") == null)?new Date[2]:getSessionAttr("checkDate"));

        if((cart == null)?false:!cart.getItems().isEmpty()) {
            OrderList orders = new OrderList();
            orders.setOrderTime(new Date());
            orders.setUser(user);

            for (OrderDetail orderitem : cart.getItems().values()) {
                orderitem.setOrderList(orders);
                orders.getOrderDetails().add(orderitem);
            }
            if(!(checkDate[0] == null || checkDate[1] == null)) {
                orders.setTotalPrice(cart.getTotalPricePerDay()* DateUtil.differentDaysByMillisecond(checkDate[0], checkDate[1]));
            }
            orders.setTotalQty(cart.getTotalQty());
            orders.setNumber(cart.getNum());

            Collection<Object> orderitems = new HashSet<>(0);
            for (OrderDetail orderitem : orders.getOrderDetails()) {
                Map<String, Object> items = new HashMap<>(0);
                items.put("roomTypeId", orderitem.getRoomTypeId());
                items.put("qty", orderitem.getQty());
                items.put("roomTypeName", orderitem.getRoomType().getTypeName());
                items.put("price", orderitem.getRoomType().getPrice());
//                items.put("discount", orderitem.getRoomType().getDiscount());
                orderitems.add(items);
            }
            setAttr("orders",orders);
            setAttr("data",orderitems);
            setAttr("result", true);
        }else{
            setAttr("result", false);
            setAttr("msg", "订单为空！");
        }
        setAttr("orderStatus",getSessionAttr("orderStatus"));
        setAttr("checkDate",getSessionAttr("checkDate"));
        renderJson();
    }


    public void add() {
        //render("add.html");  //（默认对应add.html，否则需显性指定，如render("addRoomType.html")）
    }

    public void addRoomTypeToCart() {
        RoomType roomType = RoomTypeController.service.findRoomTypeById(getParaToInt("id"));
        OrderDetail orderitem = new OrderDetail();
        orderitem.setRoomType(roomType);
        orderitem.setQty(getParaToInt("qty"));
        Cart cart = (Cart) ((getSessionAttr("cart") == null)?new Cart():getSessionAttr("cart"));
        cart.addRoomType(getParaToInt("id"), orderitem);

        setSessionAttr("cart", cart);
        setAttr("result", true);
        setAttr("msg", "添加成功！");
        renderJson();
    }
    public void addCustomerToCart() {
        Customer customer = CustomerController.service.findCustomerById(getParaToInt("customerId"));
        OrderDetailCustomer orderDetailCustomer = new OrderDetailCustomer();
        orderDetailCustomer.setCustomer(customer);
        Cart cart = (Cart) ((getSessionAttr("cart") == null)?new Cart():getSessionAttr("cart"));
        if(cart.addCustomer(getParaToInt("customerId"), orderDetailCustomer)){
            setAttr("result", true);
            setAttr("msg", "添加成功！");
        }else{
            setAttr("result", false);
            setAttr("msg", "已添加！");
        }
        setSessionAttr("cart", cart);

        renderJson();
    }
    public void addRoomToCart() {
        Room room = RoomController.service.findRoomById(getParaToInt("roomId"));
        OrderDetailRoom orderDetailRoom = new OrderDetailRoom();
        orderDetailRoom.setRoom(room);
        Cart cart = (Cart) ((getSessionAttr("roomCart") == null)?new Cart():getSessionAttr("roomCart"));
        int orderListId = getParaToInt("orderListId");
        int totalQty = OrderListController.service.findOrderListById(orderListId).getTotalQty();
        if(cart.getList().isEmpty()||cart.getList().get(orderListId)==null||cart.getList().get(orderListId).size() < totalQty) {
            if (cart.addRoom(orderListId, getParaToInt("roomId"), orderDetailRoom)) {
                setAttr("result", true);
                setAttr("msg", "分配成功！");
            } else {
                setAttr("result", false);
                setAttr("msg", "已分配！");
            }
        } else {
            setAttr("result", false);
            setAttr("msg", "已分配完！");
        }
        setSessionAttr("roomCart", cart);

        renderJson();
    }
    public void addOrderStatusAndDate(){
        OrderStatus orderStatus = OrderStatusController.service.findOrderStatusById(getParaToInt("orderStatusId"));
        Date[] checkDate = {getParaToDate("checkin"),getParaToDate("checkout")};
        setSessionAttr("orderStatus", orderStatus);
        setSessionAttr("checkDate", checkDate);
        if(!(orderStatus == null || checkDate[0] == null || checkDate[1] == null)){
            setAttr("result", true);
            setAttr("msg", "订单状态和预订日期更新成功!");
        }else{
            setAttr("result", false);
            setAttr("msg", "更新失败!，请填写完整！");
        }
        renderJson();
    }

    public void clearCart() {
        Cart cart = getSessionAttr("cart");
        cart.clearCart();
        setSessionAttr("cart", cart);
        setAttr("result", true);
        setAttr("msg", "清空成功！");
        renderJson();
    }
    /**
     * 订单提交
     */
    public void submitOrders() {
        User user = UserController.service.findUserByName((String) getSessionAttr("loginUserName"));
        OrderStatus orderStatus = getSessionAttr("orderStatus");
        Date[] checkDate = getSessionAttr("checkDate");
        Cart cart = getSessionAttr("cart");
        if(!(orderStatus == null || checkDate[0] == null || checkDate[1] == null)){
            if ((cart != null) && !(cart.getItems().isEmpty() || cart.getCustomers().isEmpty())) {
                OrderList orders = new OrderList();
                    orders.setUser(user);
                    orders.setOrderStatus(orderStatus);
                    orders.setOrderTime(new Date());
                    orders.setPricePerDay(cart.getTotalPricePerDay());
                    orders.setTotalPrice(cart.getTotalPricePerDay()* DateUtil.differentDaysByMillisecond(checkDate[0], checkDate[1]));
                    orders.setCheckin(checkDate[0]);
                    orders.setCheckout(checkDate[1]);
                    orders.setDelayDays(0);
                    orders.setNewCheckout(checkDate[1]);
                    orders.setNumber(cart.getNum());
                    orders.setTotalQty(cart.getTotalQty());
                    Double cashPledge = Math.ceil(orders.getTotalPrice()/100.0);
                    orders.setCashPledge(cashPledge.intValue()*100);
                OrderListController.service.addOrderList(orders);
                orders = OrderListController.service.findOrderListByDateTime(orders.getOrderTime());
                for (OrderDetail orderitem : cart.getItems().values()) {
                    orderitem.setOrderList(orders);
                    OrderDetailController.service.addOrderDetail(orderitem);
                    orders.getOrderDetails().add(orderitem);
                }
                for (OrderDetailCustomer orderDetailCustomer : cart.getCustomers().values()) {
                    orderDetailCustomer.setOrderList(orders);
                    OrderDetailCustomerController.service.addOrderDetailCustomer(orderDetailCustomer);
                    orders.getOrderDetailCustomers().add(orderDetailCustomer);
                }
                setAttr("result", true);
                setAttr("msg", "提交订单成功!");
                cart.clearCart();
                setSessionAttr("cart", cart);
                removeSessionAttr("orderStatus");
            } else{
                setAttr("result", false);
                setAttr("msg", "提交失败，订单为空或没有客户入住!");
            }
        }else{
            setAttr("result",false);
            setAttr("msg", "提交失败，请选择订单状态以及添加入离日期!");
        }
        renderJson();
    }
    /**
     * 取消入住
     */
    public void cancel(){
        int id=this.getParaToInt("id");
        Cart cart = getSessionAttr("roomCart");
        if (OrderListController.service.checkInOrderList(id, 4)) {
            setAttr("result", true);
            setAttr("msg", "取消入住成功!");
            cart.clearRoomCart(id);
            setSessionAttr("roomCart", cart);
        } else{
            setAttr("result", false);
            setAttr("msg", "取消入住失败!");
        }
        renderJson();
    }
    /**
     * 入住登记
     */
    public void checkin(){
        int id=this.getParaToInt("id");
        OrderList orders = OrderListController.service.findOrderListById(id);
        Cart cart = getSessionAttr("roomCart");
        if ((cart != null) && !(cart.getList().isEmpty())&&cart.getList().get(id)!=null&&cart.getList().get(id).size()==orders.getTotalQty()) {
            OrderListController.service.checkInOrderList(id, 3);
            for (OrderDetailRoom orderitem : cart.getList().get(id).values()) {
                orderitem.setOrderList(orders);
                OrderDetailRoomController.service.addOrderDetailRoom(orderitem);
                Room room = orderitem.getRoom();
                RoomController.service.updateRoom(room.setRoomStatusId(5));
                orders.getOrderDetailRooms().add(orderitem);
            }
            setAttr("result", true);
            setAttr("msg", "入住登记成功!");
            cart.clearRoomCart(id);
            setSessionAttr("roomCart", cart);
        } else{
            setAttr("result", false);
            setAttr("msg", "入住登记失败，没有分配完房间!");
        }
        renderJson();
    }
    /**
     * 订单结账
     */
    public void checkout(){
        OrderList orderList = getModel(OrderList.class);
        OrderList orders = OrderListController.service.findOrderListById(orderList.getId());
        Double change = orders.getCashPledge() + orderList.getPayAmount() - orders.getTotalPrice();
        if(OrderListController.service.updateOrderList(orderList.setChange(change))&&OrderListController.service.checkOutOrderList(orderList.getId(), 2)){
            for (OrderDetailRoom orderitem : orders.findAllRooms(orders.getId())) {
                Room room = orderitem.getRoom();
                RoomController.service.updateRoom(room.setRoomStatusId(2));
            }
            setAttr("result", true);
            setAttr("msg", "订单结账成功!\n找零" + change + "元!");
        }else {
            setAttr("result", false);
            setAttr("msg", "订单结账失败!");
        }
        renderJson();
    }
    public void detailRoom(){
        Cart cart = getSessionAttr("roomCart");
        Collection<Object> allRooms = new HashSet<>(0);
        if ((cart != null) && !cart.getList().isEmpty()) {
            for (Map<Integer, OrderDetailRoom> rooms : cart.getList().values()) {
                for(OrderDetailRoom orderDetailRoom : rooms.values()) {
                    Map<String, String> items = new HashMap<>(0);
                    Room room = orderDetailRoom.getRoom();
                    items.put("id", String.valueOf(room.getId()));
                    items.put("roomNumber", room.getRoomNumber());
                    items.put("typeName", RoomTypeController.service.findRoomTypeById(room.getRoomTypeId()).getTypeName());
                    items.put("statusName", RoomStatusController.service.findRoomStatusById(room.getRoomStatusId()).getStatusName());
                    allRooms.add(room);
                }
            }
        }
        setAttr("data", allRooms);
        renderJson();
    }
    public void detailCustomer(){
        Cart cart = getSessionAttr("cart");
        Collection<Object> customers = new HashSet<>(0);
        if ((cart != null) && !cart.getCustomers().isEmpty()) {
            for (OrderDetailCustomer orderDetailCustomer : cart.getCustomers().values()) {
                Customer customer = orderDetailCustomer.getCustomer();
                customers.add(customer);
            }
        }
        setAttr("data", customers);
        renderJson();
    }
    public void eachDetailRoom(){
        Cart cart = getSessionAttr("roomCart");
        Collection<Object> eachRooms = new HashSet<>(0);
        if ((cart != null) && !cart.getList().isEmpty()) {
            Map<Integer, OrderDetailRoom> rooms = cart.getList().get(getParaToInt("orderListId"));
            System.out.println(rooms!=null);
            if(rooms != null) {
                for (OrderDetailRoom orderDetailRoom : rooms.values()) {
                    Map<String, String> items = new HashMap<>(0);
                    Room room = orderDetailRoom.getRoom();
                    items.put("id", String.valueOf(room.getId()));
                    items.put("roomNumber", room.getRoomNumber());
                    items.put("typeName", RoomTypeController.service.findRoomTypeById(room.getRoomTypeId()).getTypeName());
                    items.put("statusName", RoomStatusController.service.findRoomStatusById(room.getRoomStatusId()).getStatusName());


                    eachRooms.add(items);
                }
            }
        }
        setAttr("data", eachRooms);
        renderJson();
    }
    public void removeRoomType(){
        Cart cart = getSessionAttr("cart");
        cart.removeRoomType(getParaToInt("roomTypeId"));
        setAttr("result", true);
        setAttr("msg", "取消房间预订成功！");
        setSessionAttr("cart", cart);
        renderJson();
    }
    public void removeCustomer(){
        Cart cart = getSessionAttr("cart");
        cart.removeCustomer(getParaToInt("customerId"));
        setAttr("result", true);
        setAttr("msg", "取消客户成功！");
        setSessionAttr("cart", cart);
        renderJson();
    }
    public void updateCart() {
        Cart cart = getSessionAttr("cart");
        cart.updateCart(getParaToInt("roomTypeId"),getParaToInt("newRoomTypeId"), getParaToInt("qty"));
        setSessionAttr("cart", cart);
        setAttr("result", true);
        setAttr("msg", "修改成功！");
        renderJson();
    }

    public void view_addOrderStatusAndDate(){
        setAttr("orderStatus",OrderStatus.dao.findAll());//分配前得到所有房间
        render("addOrderStatusAndDate.html");
    }
    public void view_addRoomType(){
        setAttr("roomType", RoomType.dao.findAll());
        render("addRoomType.html");
    }
    public void view_addCustomer(){
        setAttr("customer", Customer.dao.findAll());
        render("addCustomer.html");
    }
    public void view_addRoom(){
        setAttr("roomTypeId", getPara("roomTypeId"));
        setAttr("orderListId", getPara("orderListId"));
        render("addRoom.html");
    }
    public void view_detailCustomer(){
        render("detailCustomer.html");
    }
    public void view_eachDetailRoom(){
        setAttr("orderListId",getParaToInt("orderListId"));
        render("eachDetailRoom.html");
    }
    public void view_updateCart() {
        Cart cart = getSessionAttr("cart");
        setAttr("orderitem", cart.getItems().get(getParaToInt("roomTypeId")));
        setAttr("roomType", RoomTypeController.service.findAllRoomType());
        render("updateCart.html");
    }



}
